//
//  MKWAsyncTask.m
//  MilkyWayReader
//
//  Created by Quoc Dung Chu on 31/03/12.
//  Copyright (c) 2012 Milky Way Mobile. All rights reserved.
//

#import "MKWAsyncTask.h"
@interface MKWAsyncTask()
@property (nonatomic, copy) DoBeginAction doBeginAction;
@property (nonatomic, copy) DoInBackgroundAction doInBackgroundAction;
@property (nonatomic, copy) DoProgressAction doProgressAction;
@property (nonatomic, copy) DoFinishAction doFinishAction;
- (void) _executeInBackground;
- (void) _executeDoFinishInMainThread;
@end 


@implementation MKWAsyncTask
@synthesize doBeginAction;
@synthesize doInBackgroundAction;
@synthesize doProgressAction;
@synthesize doFinishAction;
@synthesize delegate;

+ (MKWAsyncTask *) createWithDoBeginAction: (DoBeginAction) doBeginAction_ 
                      doInBackgroundAction: (DoInBackgroundAction) doInBackgroundAction_
                          doProgressAction: (DoProgressAction) doProgressAction_ 
                            doFinishAction: (DoFinishAction) doFinishAction_ 
{
    MKWAsyncTask * asyncTask = [MKWAsyncTask new];
    asyncTask.doBeginAction = doBeginAction_;
    asyncTask.doInBackgroundAction = doInBackgroundAction_;
    asyncTask.doProgressAction = doProgressAction_;
    asyncTask.doFinishAction = doFinishAction_;
    
    return asyncTask;
}



- (void) execute
{
    self.doBeginAction ();
    [self performSelectorInBackground:@selector(_executeInBackground) withObject:nil];
}

- (void) _executeInBackground
{
    @autoreleasepool {
        self.doInBackgroundAction ();
        [self performSelectorOnMainThread:@selector(_executeDoFinishInMainThread) withObject:nil waitUntilDone:NO];
    }
    
}

- (void) _executeDoFinishInMainThread
{
    self.doFinishAction();
    [self.delegate didMKWAsyncTaskFinshExecute:self];
}

@end
